package com.hunan.api.catv.exception;

import com.google.gson.JsonObject;
import com.hunan.api.catv.action.BaseAction;
import com.hunan.api.catv.entity.Result;
import com.hunan.api.catv.entity.enums.DingType;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.utils.GsonUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@ControllerAdvice
public class GlobalExceptionHandler extends BaseAction {

    @Autowired
    AmqpTemplate amqpTemplate;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e, HttpServletResponse response, HttpServletRequest request) {

        JsonObject text = new JsonObject();
        text.addProperty("path", request.getRequestURI());
        text.addProperty("paras", GsonUtils.toJson(request.getParameterMap()));
        text.addProperty("msg", e.getMessage());
        JsonObject msg = new JsonObject();
        msg.addProperty("type", DingType.api.getCode());
        msg.addProperty("text", text.toString());
        amqpTemplate.convertAndSend(MqConstants.ding_warning_exchange, MqConstants.ding_warning_key, msg.toString());
        log.error("GlobalExceptionHandler", e);
        return buildFail("", e.getLocalizedMessage().toString());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result exceptionHandler(MethodArgumentTypeMismatchException e, HttpServletResponse response) {

        log.error("RequestParamterError method: {}  params:{} error:{} ", e.getParameter().getMethod().getName(), e.getName(), e.getLocalizedMessage(), e);

        return buildRequire("require " + e.getRequiredType() + " " + e.getName());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result exceptionHandler(ConstraintViolationException e, HttpServletResponse response) {
        String msg = "";
        Set<ConstraintViolation<?>> cves = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : cves) {
            msg = constraintViolation.getMessage();
        }
        log.error("ConstraintViolationException {} {}", e.getLocalizedMessage(), msg, e);
        return buildRequire(msg);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleValidationExceptions(
            BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return buildRequire(GsonUtils.toJson(errors));
    }


}
